<template>
  <div class="item">
    <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" @change="handleCheckAllChange">
      全选
    </el-checkbox>
    <el-checkbox-group v-model="selectedData" @change="handleSelectedDataChange">
      <el-checkbox v-for="o in options" :key="o.value" v-bind="o">
        {{ o.label }}
      </el-checkbox>
    </el-checkbox-group>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed } from 'vue';

interface Props {
  modelValue: any
  options: ObjectAny[]
}
const props = withDefaults(defineProps<Props>(), {})
const emit = defineEmits(['update:modelValue', 'change'])

const checkAll = ref(false)
const isIndeterminate = ref(false)
const selectedData = computed({
  get() {
    return props.modelValue
  },
  set(value) {
    emit('update:modelValue', value)
    emit('change', value)
  }
})

const handleCheckAllChange = (val: any) => {
  selectedData.value = val ? props.options.filter(o => !o.disabled).map(o => o.label) : []
  isIndeterminate.value = false
}
const handleSelectedDataChange = (value: any[]) => {
  const checkedCount = value.length
  checkAll.value = checkedCount === props.options.filter(o => !o.disabled).length
  isIndeterminate.value = checkedCount > 0 && checkedCount < props.options.filter(o => !o.disabled).length
}
</script>
<style lang="scss" scoped>
.item {
  >* {
    display: inline-block;
    vertical-align: top;
  }

  &>:first-child {
    display: inline-flex;
    align-items: center;
    margin-right: 30px;
  }
}
</style>